package com.kuang.servlet;

import com.alibaba.fastjson2.JSONArray;
import com.kuang.pojo.Role;
import com.kuang.pojo.User;
import com.kuang.service.role.RoleService;
import com.kuang.service.role.RoleServiceImpl;
import com.kuang.service.user.UserService;
import com.kuang.service.user.UserServiceImpl;
import com.kuang.utils.Constants;
import com.kuang.utils.PageSupport;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("进入");
        String method=req.getParameter("method");
        if(method.equals("savepwd")){
            this.updatePassword(req,resp);
        }else if (method.equals("pwdmodify")){
            this.pwdModify(req,resp);
        }else if(method.equals("query")){
            this.getUserList(req,resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }


    public void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user=(User)req.getSession().getAttribute(Constants.USER_SESSION);
        String newPassword=req.getParameter("newpassword");
        boolean flag = false;

        if( user!=null && !StringUtils.isNullOrEmpty(newPassword) ){
            UserService userService = new UserServiceImpl();
            flag=userService.updatePassword(user.getUserId(), newPassword);
            if(flag){
//                修改密码成功，移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
                req.setAttribute(Constants.MESSAGE,"修改密码成功，请退出，用新密码登录");
                resp.sendRedirect(req.getContextPath()+"/jsp/pwdmodify.jsp");
            }else {
                req.setAttribute(Constants.MESSAGE,"修改密码失败");
            }
        }else {
            req.setAttribute(Constants.MESSAGE,"新密码为空");
        }
    }


    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword=req.getParameter("oldpassword");

        Map<String,String> resultMap = new HashMap<String,String>();
        if(user == null){
//                session失效
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){
//                旧密码为空
            resultMap.put("result","error");
        }else {
            if(user.getUserPassword().equals(oldpassword)){
//                    旧密码正确
                resultMap.put("result","true");
            }else {
//                    旧密码错误
                resultMap.put("result","false");
            }
        }
        PrintWriter writer = null;

        try {
            resp.setContentType("application/json");

            writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.close();
        }



    }

    public void getUserList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RoleService roleService = new RoleServiceImpl();
        UserService userService = new UserServiceImpl();

        String userName=req.getParameter("queryname");
        String roleCode=req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
//            String currentPageNo = req.getParameter("currentPageNo");

//            if(roleCode==null || roleCode.equals("")){
//                roleCode="0";
//            }

//            if(StringUtils.isNullOrEmpty(currentPageNo)){
//                currentPageNo= String.valueOf(0);
//
//            }

        if (StringUtils.isNullOrEmpty(pageIndex)){
            pageIndex="1";
        }



        int pageSize =Constants.pageSize;

        PageSupport pageShow = new PageSupport();
        pageShow.setPageSize(pageSize);
        pageShow.setCurrentPageNo(Integer.parseInt(pageIndex));


        List<Role> roleList=roleService.getRoleList();
        List<User> userList = userService.getUserList(userName,roleCode,pageShow.getPageSize(),pageShow.getCurrentPageNo());


        List<User> userTotal=userService.getUserTotal(userName,roleCode);
        PageSupport page = new PageSupport();
//            设置页容量
        page.setPageSize(pageSize);
//            设置当前页
        page.setCurrentPageNo(Integer.parseInt(pageIndex));
//            设置总数
        page.setTotalCount(userTotal.size());
        req.setAttribute("totalCount",page.getTotalCount());
        req.setAttribute("currentPageNo",page.getCurrentPageNo());
        req.setAttribute("totalPageCount",page.getTotalPageCount());


        req.setAttribute("roleList",roleList);
        req.setAttribute("userList",userList);
        req.getRequestDispatcher("/jsp/userlist.jsp").forward(req,resp);


    }
}
